﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace PollSystemService
{
    
    public class PollServices : IPollService
    {
        public IEnumerable<PollDTO> GetPolls()
        {
            PollDbEntities entities = new PollDbEntities();
            IEnumerable<Poll> polls = entities.Polls.Include("Answers");
            List<PollDTO> result = new List<PollDTO>();
            foreach (var poll in polls)
            {
                List<string> answers = AnswersToStringList(poll.Answers);
                result.Add(new PollDTO() {pQuestion=poll.Question, pAnswers=answers });
            }
            return result;
        }

        public IEnumerable<AnswerDTO> GetVotes(Vote vote)
        {
            string pollName=vote.Question;
            string selectedAnswer = vote.Answer;
            PollDbEntities entities = new PollDbEntities();
            Poll voted = entities.Polls.Include("Answers").First(p=>p.Question== pollName);
            voted.TotalVotes++;
            Answer answer = voted.Answers.First(a => a.Text == selectedAnswer);
            answer.Votes++;
            entities.SaveChanges();
            IEnumerable<AnswerDTO> answers = ExtractAnswerDTOList(voted);
            return answers;

        }

        private List<AnswerDTO> ExtractAnswerDTOList(Poll votedOn) 
        {
            List<AnswerDTO> answers = new List<AnswerDTO>();
            foreach (var answer in votedOn.Answers)
            {
                string text = answer.Text;
                int percent = (answer.Votes*100) / votedOn.TotalVotes;
                double votes = votedOn.TotalVotes;
                if(((answer.Votes*100) % votedOn.TotalVotes)/votes>0.5)
                {
                    percent++;
                }
                
                answers.Add(new AnswerDTO() { Text = text, Votes = percent });
            }
            return answers;
        }


        private List<string> AnswersToStringList(IEnumerable<Answer> answers) 
        {
            List<string> answersAsStrings = new List<string>();
            foreach (var answer in answers)
            {
                answersAsStrings.Add(answer.Text);
            }
            return answersAsStrings;
        }
    }
}
